package com.steven.door.activity;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.example.x6.serial.SerialPort;
import com.steven.door.R;
import com.steven.door.base.Constant;
import com.steven.door.base.SerialCode;
import com.steven.door.entity.SocketSendMsg;
import com.steven.door.services.WebSocketService;
import com.steven.door.socket.AndroidSocketClient;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class TestActivity extends Activity implements SerialCode {
    private SerialPort serialTtyS2;
    private InputStream ttyS1InputStream;
    private OutputStream ttyS1OutputStream;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

    }

    //连接webSocket
    public void connection(View view) {
        startService(new Intent(this, WebSocketService.class));

    }

    //打开串口
    public void openSerialPort(View view) {
        try {
            File pathFile = new File(serialPath);
            serialTtyS2 = new SerialPort(pathFile, baudRate, flag);
            ttyS1InputStream = serialTtyS2.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送指令开门
    public void click(View view) {
        try {
            byte[] open = {(byte) 0xE7, (byte) 0xFF, 0x01, 0x01, 0x01, 0x03, 0x00, 0x7E};
            ttyS1OutputStream = serialTtyS2.getOutputStream();
            ttyS1OutputStream.write(open);
            ttyS1OutputStream.flush();
            ttyS1OutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void save(View view) {
    }

    //删除
    public void delete(View view) {
    }

    //测试socket链接
    public void socketConnect(View view) {
        AndroidSocketClient.getInstance(this).localConnect();
    }

    //发送信息
    public void sendMsg(View view) {
        SocketSendMsg socketSendMsg = new SocketSendMsg();
        socketSendMsg.setFrom("123");
        socketSendMsg.setTo("456");
        socketSendMsg.setMsg("fun!");
        AndroidSocketClient.getInstance(this).sendMessage(JSON.toJSONString(socketSendMsg));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AndroidSocketClient.getInstance(this).logout();
    }
}
